package com.java.distributed.controller;

import com.java.distributed.beans.CommonResult;
import com.java.distributed.beans.MySession;
import com.java.distributed.beans.User;
import com.java.distributed.filter.LoginFilter;
import com.java.distributed.service.MySessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


@RestController
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    private Map<String,String> account;

    @Autowired
    private MySessionService mySessionService;

    @PostConstruct
    public void init() {
        account = new HashMap<>();
        account.put("zs","a111111");
        account.put("ls","a111111");
        account.put("ww","a111111");
        account.put("zl","a111111");
    }

    @PostMapping("/login")
    public CommonResult login(HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password){
        LOGGER.info("login userName = {}" ,userName);
        if (password.equals(account.get(userName))){
            //密码正确
            //设置session
            HttpSession session = request.getSession();
            User user = new User(null,userName,null);
            session.setAttribute("currentUser",user);
            //返回成功
            return new CommonResult();
        }
        //密码错误
        return new CommonResult(false,"用户名密码错误",null,"S100000001");
    }


    @PostMapping("/loginV2")
    public CommonResult loginV2(HttpServletRequest request, HttpServletResponse response, @RequestParam String userName, @RequestParam String password){
        LOGGER.info("login userName = {}" ,userName);
        if (password.equals(account.get(userName))){
            //密码正确
            //设置session
            MySession session = mySessionService.getSession(request,response);
            User user = new User(null,userName,null);
            session.setAttribute("currentUser",user);
            mySessionService.setSession(session);
            //返回成功
            return new CommonResult();
        }
        //密码错误
        return new CommonResult(false,"用户名密码错误",null,"S100000001");
    }
}
